/* ServerContoller.java
 * Allows the user to start a stream server, select file(s) to
 * boradcast, and stop the stream server
 */

package com.redribbon.droidnoise;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio.AudioColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class ServerController extends Activity {
	
	private static final String MEDIA_PATH = new String("/sdcard/");
	private ArrayList<SongContainer> songs = new ArrayList<SongContainer>();
	private MediaPlayer mp = new MediaPlayer();
	private int currentPosition = 0;
	private ListView s2_list_view;
	SimpleCursorAdapter adapter;
	ArrayAdapter<SongContainer> songList;
	
	private boolean isStreaming;
	
	private String stationName;
	private int port;
	
	Button s2_start_button;
	    
	class Mp3Filter implements FilenameFilter {
		public boolean accept(File dir, String name) {
			return (name.endsWith(".mp3"));
	    }
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isStreaming = false;
        Uri data = getIntent().getData();
        //TODO Pass data
        setupGUI();
    }
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstaceState) {
		super.onRestoreInstanceState(savedInstaceState);
		isStreaming = savedInstaceState.getBoolean("isStreaming");
	}

	@Override
	protected void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		savedInstanceState.putBoolean("isStreaming", isStreaming);
	}
	
	private void setupGUI() {
        setContentView(R.layout.server_2);
        
        
        s2_list_view = (ListView)findViewById(R.id.server_2_listview);
        
       	final Button s2_back_button = (Button) findViewById(R.id.server_2_back_button);
        s2_back_button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
            	finish();
            }
        });
        
        final Button s2_add_song_button = (Button)findViewById(R.id.server_2_add_song_button);
        s2_add_song_button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
            	
            	Intent intent = new Intent(ServerController.this, SongPicker.class);
            	startActivityForResult(intent, 0);
            }
        });
        
        s2_start_button = (Button)findViewById(R.id.server_2_start_button);
        setupStartButton();
        
        updateSongList();
	}
	
	private void setupStartButton() {
		if (isStreaming) {
			s2_start_button.setText(R.string.stop_streaming);
			s2_start_button.setOnClickListener(mStopListener);
		}
		else {
			s2_start_button.setText(R.string.start_streaming);
			s2_start_button.setOnClickListener(mStartListener);
		}
	}
	
      public void updateSongList() {
    	  /*
          File home = new File(MEDIA_PATH);
          if (home.listFiles(new Mp3Filter()).length > 0) {
              for (File file : home.listFiles(new Mp3Filter())) {
                  songs.add(file.getName());
              }*/
       
              songList = new ArrayAdapter<SongContainer>(this,
                      R.layout.song_title, songs);
              s2_list_view.setAdapter(songList);
          //}
      }

    private OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v) {
            // Make sure the service is started.  It will continue running
            // until someone calls stopService().
        	NoiseConstants.songs_to_stream = songs;
            startService(new Intent(ServerController.this, StreamServer.class));
            isStreaming = true;
            setupStartButton();
        }
    };

    private OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            // Cancel a previous call to startService().  Note that the
            // service will not actually stop at this point if there are
            // still bound clients.
            stopService(new Intent(ServerController.this, StreamServer.class));
            isStreaming = false;
            setupStartButton();
        }
    };
    
    public void onActivityResult(int request_code, int result_code, Intent intent) {
    	
    	if ((result_code < 0)&&(!isStreaming)) // if user picked a song
    	{
	    	
	    	Uri uri = intent.getData();
	    	String[] columns = new String[] { AudioColumns._ID, AudioColumns.TITLE, AudioColumns.ARTIST,
	    			AudioColumns.ALBUM, AudioColumns.DURATION, AudioColumns.DATA, AudioColumns.SIZE};
	    	Cursor cursor = getContentResolver().query(uri, columns, null, null, null);
	   
	  	  	cursor.moveToFirst();
	  	  	
	  	  	
	  	  	String title = cursor.getString(cursor.getColumnIndexOrThrow(AudioColumns.TITLE));
	  	  	String artist = cursor.getString(cursor.getColumnIndexOrThrow(AudioColumns.ARTIST));
	  	  	String album = cursor.getString(cursor.getColumnIndexOrThrow(AudioColumns.ALBUM));
	  	  	Long duration = cursor.getLong(cursor.getColumnIndexOrThrow(AudioColumns.DURATION));
	  	  	ByteArrayInputStream data = new ByteArrayInputStream(cursor.getBlob(cursor.getColumnIndexOrThrow(AudioColumns.DATA)));
	  	  	Long size = cursor.getLong(cursor.getColumnIndexOrThrow(AudioColumns.SIZE));
	  	  	
	  	  	Log.i("taylor song data", cursor.getBlob(cursor.getColumnIndexOrThrow(AudioColumns.DATA)).toString());
	  	  	
	  	  	SongContainer new_song = new SongContainer(title, artist, album, duration, size, data);
	  	  	
	  	  	if (not_already_added(new_song)) {
	  	  		songs.add(new_song);
	  	  		songList.notifyDataSetChanged();
	  	  	}
    	}
    	if (isStreaming){
    		Toast.makeText(this, "Sorry, currently streaming", Toast.LENGTH_SHORT).show();
    	}
    }
    
    public boolean not_already_added(SongContainer new_song) {
    	for (SongContainer song : songs) {
    		if ((song.title.equals(new_song.title))&&(song.duration.equals(new_song.duration)))
    			return false;
    	}
    	return true;
    }
}
